package com.lagou.rpc.server.service;

import com.lagou.common.service.UserService;
import com.lagou.common.util.JSONSerializer;
import com.lagou.common.util.RpcDecoder;
import com.lagou.common.util.RpcRequest;
import com.lagou.common.util.RpcService;
import com.lagou.common.zk.ServiceCenter;
import com.lagou.rpc.server.handler.UserServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Value("${custom.rpc.server.name}")
    private String serverName;

    @Override
    public String sayHello(String word) {
        String result = "sayHello: " + word;
        System.out.println(result);
        return serverName + " " + result;
    }

    public static void startService(RpcService rpcService) throws Exception {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new UserServerHandler());

                    }
                });
        serverBootstrap.bind(rpcService.getHostname(), rpcService.getPort()).sync();

        // 1. 启动2个服务端，可以将IP及端口信息自动注册到Zookeeper
        ServiceCenter.registerService(rpcService);
    }
}
